#include "netmain.h"
#include <QTcpSocket>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QDebug>
NetMain *NetMain::obj = nullptr;

NetMain::NetMain(QObject *parent)
    : QObject{parent}
    , client(new QTcpSocket)
{
    connect(client, &QTcpSocket::readyRead,
            this, &NetMain::clientReadyReadSlot);
    connectToHost();
}

NetMain *NetMain::getObject()
{
    if(obj == nullptr)
        obj = new NetMain;
    return obj;
}

void NetMain::userLogin(QString username, QString password)
{
    connectToHost();
    QJsonObject obj;
    obj.insert("type", 3001);
    obj.insert("username", username);
    obj.insert("password", password);
    client->write(QJsonDocument(obj).toJson());
}

void NetMain::userRegister(QString username, QString password)
{

}

void NetMain::getDeviceValue(int deviceTypeId, int deviceTypeIndex)
{

}

void NetMain::clientReadyReadSlot()
{
    QByteArray data = client->readAll();
    int count = 0;  //当前括号数量
    int start = -1; //开始的索引
    for(int i = 0; i < data.length(); i++)
    {
        if(data.at(i) == '{')
        {
            count++;
            if(start == -1)
            {
                start = i;
            }
        }
        else if(data.at(i) == '}')
        {
            count--;
            if(count == 0)
            {
                QByteArray temp = data.mid(start, i-start+1);
                start = -1;
                QJsonObject obj = QJsonDocument::fromJson(temp).object();
                handleFrame(obj);
            }
        }
    }
}

void NetMain::connectToHost()
{
    if(client->state() == QTcpSocket::ConnectedState)
        return;
    client->connectToHost("127.0.0.1", 10087);
    client->waitForConnected(1000);
}

void NetMain::handleFrame(const QJsonObject &obj)
{
    int type = obj.value("type").toInt();
    if(type == 4001)
        handleLoginReFrame(obj);
    else if(type == 4002)
        handleRegisterReFrame(obj);
    else if(type == 4011)
        handleDeviceValueFrame(obj);
}

void NetMain::handleLoginReFrame(const QJsonObject &obj)
{
    bool re = obj.value("re").toBool();
    emit userLoginRe(re);
}

void NetMain::handleRegisterReFrame(const QJsonObject &obj)
{

}

void NetMain::handleDeviceValueFrame(const QJsonObject &obj)
{
    int deviceTypeId = obj.value("device_type_id").toInt();
    int deviceTypeIndex = obj.value("device_type_index").toInt();
    QJsonValue value = obj.value("value");
    if(value.isDouble())
        emit deviceValue(deviceTypeId, deviceTypeIndex,
                         value.toDouble());
    else if(value.isBool())
        emit deviceValue(deviceTypeId, deviceTypeIndex,
                         value.toBool());
    else if(value.isString())
        emit deviceValue(deviceTypeId, deviceTypeIndex,
                         value.toString());
}





